from flask import Blueprint, current_app, request

from controllers import R
from mauth import HasPerm
from models.dict import Dict
from services.dict_service import DictService
from validators import BasePageForm
from validators.id_validator import IdForm, IdsForm
from validators.dict_validator import DictForm

# 声明一个蓝图
dict = Blueprint("dict", __name__, url_prefix="/sys/dict")

# 声明一个字典业务服务
dict_service = DictService(model=Dict)


@dict.route("/detail", methods=["POST"])
@HasPerm(access="sys:dict:detail", name="通过id获取字典信息")
def dict_detail():
    """
    通过id获取字典信息
    :return:
    """
    form = IdForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # 或者直接拿id值 id=form.id.data
    # u = Dict.query.filter_by(id=form.id.data).first()
    # 通过主键查询
    u = dict_service.detail(form)
    if u is not None:
        return R.data(u.to_dict())
    else:
        return R.fail("该记录不存在")


@dict.route("/page", methods=["POST"])
@HasPerm(access="sys:dict:page", name="分页查询字典列表")
def dict_page():
    """
    分页查询字典列表
    :return:
    """
    form = BasePageForm()
    form.validate_for_api()
    return R.data(dict_service.page(form))


@dict.route("/save", methods=["POST"])
@HasPerm(access="sys:dict:save", name="添加字典")
def dict_save():
    """
    添加字典
    :return:
    """
    form = DictForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    dict_service.save(form)
    return R.success("添加字典成功")


@dict.route("/update", methods=["POST"])
@HasPerm(access="sys:dict:update", name="修改字典")
def dict_update():
    """
    修改字典
    :return:
    """
    form = DictForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    dict_service.update(form)
    return R.success("修改字典成功")


@dict.route("/remove", methods=["POST"])
@HasPerm(access="sys:dict:remove", name="删除字典")
def dict_remove():
    """
    删除字典
    :return:
    """
    form = IdsForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    dict_service.remove(form)
    return R.success("删除字典成功")


@dict.route("/getByDictType", methods=["POST"])
@HasPerm(name="字典下拉")
def get_by_dict_type():
    """
    字典下拉
    :return:
    """
    dictType = request.json.get("dictType")
    return R.data(dict_service.get_by_dict_type(dictType=dictType))


@dict.route("/enumDictList", methods=["POST"])
@HasPerm(name="枚举字典")
def enum_dict_list():
    """
    枚举字典
    :return:
    """
    return R.data(current_app.config["DICT_ENUM_LIST"])


@dict.route("/customDictList", methods=["POST"])
@HasPerm(name="自定义字典")
def custom_dict_list():
    """
    自定义字典
    :return:
    """
    return R.data(current_app.config["DICT_CUSTOM_LIST"])
